Page({
  data: {
    addressList: [],
    hasAddress: false,
    deliveryRange: 3 // 配送范围，单位：千米
  },

  onLoad: function (options) {
    // 加载地址列表
    this.loadAddressList();
  },

  onShow: function () {
    // 每次显示页面时刷新地址列表
    this.loadAddressList();
  },

  // 加载地址列表
  loadAddressList: function () {
    const addressList = wx.getStorageSync('addressList') || [];
    this.setData({
      addressList: addressList,
      hasAddress: addressList.length > 0
    });
  },

  // 选择地址
  selectAddress: function (e) {
    const index = e.currentTarget.dataset.index;
    const address = this.data.addressList[index];

    // 判断是否在配送范围内
    if (!this.checkDeliveryRange(address)) {
      wx.showToast({
        title: '超出配送范围',
        icon: 'none'
      });
      return;
    }

    // 保存当前选择的地址
    wx.setStorageSync('selectedAddress', address);

    // 跳转到外卖菜单页面
    wx.navigateTo({
      url: '/pages/delivery-menu/delivery-menu'
    });
  },

  // 判断是否在配送范围内（简单模拟）
  checkDeliveryRange: function (address) {
    // 这里可以接入地图API计算真实距离
    // 现在只是简单模拟，根据地址中是否包含某些关键词来判断
    const inRangeKeywords = ['附近', '小区', '大厦', '街道', '路'];
    for (let keyword of inRangeKeywords) {
      if (address.detailInfo.indexOf(keyword) !== -1) {
        return true;
      }
    }
    return true; // 为了演示，默认返回true
  },

  // 添加新地址
  addNewAddress: function () {
    wx.chooseAddress({
      success: (res) => {
        if (res.errMsg === 'chooseAddress:ok') {
          const newAddress = {
            id: Date.now(),
            name: res.userName,
            phone: res.telNumber,
            province: res.provinceName,
            city: res.cityName,
            district: res.countyName,
            detailInfo: res.detailInfo,
            isDefault: this.data.addressList.length === 0 // 第一个地址设为默认
          };

          // 添加到地址列表
          const addressList = this.data.addressList;
          addressList.push(newAddress);

          // 更新状态和本地存储
          this.setData({
            addressList: addressList,
            hasAddress: true
          });
          wx.setStorageSync('addressList', addressList);

          // 自动选中新地址并跳转
          if (this.checkDeliveryRange(newAddress)) {
            wx.setStorageSync('selectedAddress', newAddress);
            wx.navigateTo({
              url: '/pages/delivery-menu/delivery-menu'
            });
          } else {
            wx.showToast({
              title: '地址超出配送范围',
              icon: 'none'
            });
          }
        }
      },
      fail: (err) => {
        if (err.errMsg !== 'chooseAddress:fail cancel') {
          wx.showToast({
            title: '获取地址失败',
            icon: 'none'
          });
        }
      }
    });
  },

  // 手动输入地址
  inputAddress: function () {
    wx.navigateTo({
      url: '/pages/address-form/address-form?from=delivery'
    });
  }
}) 